import { mapState } from 'vuex'
const APPID = 'wx32c0dfcb4dc3fc23' // FIXME

const checkAuth = {
  data() {
    return {
      needCheckAuth: true,
      pageParams: {},
	    backUrl: '',
      indexUrl: '/pages/submit/index',
      loginUrl: '/pages/account/login',
    }
  },
  computed: {
    ...mapState('session', [
      'user',
    ]),
  },
  onLoad(opt) {
    this.pageParams = opt
	  this.backUrl = opt.backUrl || this.indexUrl
  },
  
  onShow() {
    // if (this.needCheckAuth && !this.user) {
    //   const currentPage = getCurrentPages().pop()
    //   let backUrl
    //   if (!!currentPage) {
    //     backUrl = `/${currentPage.route}?${qs.stringify(this.pageParams)}`
    //   }
     
    //   uni.navigateTo({
    //     url: `${this.loginUrl}?${qs.stringify({ backUrl })}`
    //   })
    // }
  },
  methods: {
    scanQR(cb) {
      const scanCode = () => {

        const boot = (config) => {
          const { timpstamp, noncestr, signature } = config

          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: APPID, // 必填，公众号的唯一标识
            timestamp: timpstamp, // 必填，生成签名的时间戳
            nonceStr: noncestr, // 必填，生成签名的随机串
            signature, // 必填，签名
            jsApiList: [ // 必填，需要使用的JS接口列表
              'scanQRCode'
            ]
          });

          wx.ready(() => {
            wx.scanQRCode({
              needResult: 1,
              scanType: ['qrCode'],
              success: (res) => {
                var result = res.resultStr;
                // TODO:
                cb && cb(result);
              }
            })
            // TODO: if the TICKET is Expired
          });
        }; // boot

        this.$http({
          url: `/GetSignature?url=${window.location.href}`,
          method: 'POST',
          success: (res) => {
            if (res.Success) {
              const { sig, timpstamp, nonceStr } = res.Data
              boot({
                timpstamp,
                noncestr: nonceStr,
                signature: sig
              })
            } else if (res.error) {}
          },
        }); // GetSignature

      }; // scanCode

      if (typeof wx !== 'undefined' && 'config' in wx) {
        scanCode()
      } else {
        const sc = document.createElement('script')
        sc.setAttribute('type', 'text/javascript')
        sc.setAttribute('src', 'http://res2.wx.qq.com/open/js/jweixin-1.6.0.js')
        sc.onload = scanCode
        document.head.appendChild(sc)
      }
    },
  }
}

export default checkAuth 